import { GATEWAY_URL } from "@/lib/env";
import { OrderStatus } from "@/shared/order";
class OrdersService {
  async createOrder(
    items: { id: number; quantity: number }[],
    address: string,
    count: number = 1,
    description?: string
  ) {
    try {
      const response = await fetch(`${GATEWAY_URL}/orders`, {
        method: "POST",
        body: JSON.stringify({ address, count, description, items }),
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      if (response.status !== 201) throw new Error(response.statusText);
      const data = await response.json();
      return data;
    } catch (error) {
      console.error("Error fetching orders:", error);
      throw error;
    }
  }

  async changeOrderStatus(orderId: number, status: string) {
    try {
      const response = await fetch(
        `${GATEWAY_URL}/orders/${orderId}${`?status=${status.toString()}`}`,
        {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        }
      );

      const data = await response.json();
      return data;
    } catch (error) {
      throw error;
    }
  }

  async getAllItems(status?: OrderStatus) {
    try {
      const response = await fetch(
        `${GATEWAY_URL}/orders/all${status ? `?status=${status}` : ""}`,
        {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        }
      );

      const data = await response.json();
      return data;
    } catch (error) {
      throw error;
    }
  }

  async getMyOrders() {
    try {
      const response = await fetch(`${GATEWAY_URL}/orders`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      if (response.status !== 200) throw new Error(response.statusText);
      const data = await response.json();
      return data;
    } catch (error) {
      console.error("Error fetching orders:", error);
      throw error;
    }
  }

  async getOrderItems(orderId: number) {
    try {
      const response = await fetch(`${GATEWAY_URL}/orders/${orderId}`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      const data = await response.json();
      return data;
    } catch (error) {
      console.error("Error fetching orders:", error);
      throw error;
    }
  }
}

export default new OrdersService();
